package com.lewis.service;

import java.util.UUID;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import com.lewis.entry.User;
import com.lewis.mapper.UserMapper;

@Service
public class ShiroServiceImpl {
	
	
	@Resource 
	private UserMapper userMapper;
	
	/**
	 * register
	 * @param user
	 * @throws Exception 
	 */
	public void doRegister(User user) throws Exception{
		
		//随机salt
		String uuid=UUID.randomUUID().toString().replaceAll("-","");
		//password+salt加密三次
		Md5Hash md5=new Md5Hash(user.getPassword(),uuid,3);
		user.setPassword(md5.toString());	
		user.setSalt(uuid);
		userMapper.addUser(user);
	}
	
	/**
	 * login
	 * @param user
	 */
	public void doLogin(User user){
		UsernamePasswordToken token= new UsernamePasswordToken(user.getUsername(),user.getPassword());
		Subject subject=SecurityUtils.getSubject();
		System.out.println("&&&&&&&&&&&&&&&&&&&&&&&hasRole->admin:");
		try{
			//认证，授权
			//token.setRememberMe(true);
			subject.login(token);
			subject.checkRole("admin");
			subject.checkPermission("user:add");
		}catch(IncorrectCredentialsException e){
			//System.out.println("***********************************************"+e.getMessage());
			throw new RuntimeException("password err"); 
		}
		
	}
	
}
